﻿# -*- coding:utf-8 -*-
# 
#  импорт списка сотрудников ГИМ
#
import math
from collections import defaultdict
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError, AppCommand, NoArgsCommand
from django.db.models.loading import get_app, get_model



class Command( NoArgsCommand ):

    #help = 'Import department from Sklad app to SHM  app.'
    requires_model_validation = True
    
    def handle_noargs(self, **options):
        from django.db.models import get_models
        # Выполнение всех операций в одной транзакции
        from django.db import transaction
        transaction.enter_transaction_management()
        try:
            transaction.managed(True)
            self.update_employee()
            transaction.commit()
        finally:
            transaction.rollback()
            transaction.leave_transaction_management()     



    def update_employee(self):    
        print "Update employee list..."
        Employee = get_model('shm', 'Employee')
        Department = get_model('shm', 'Department')

        for line in open("shm_dept_employee1.csv"):
            uline = unicode(line, "CP1251").split(';', 3)
            
            if len(uline) == 3:
                
                code = uline[0]
                name = uline[1].replace(' ','',1)
                post = uline[2].replace('\n','').replace(' ','',1)
                
                names= name.split(' ', 3)
                
                last_name = names[0]
                first_name = names[1]
                if len(names) > 2:
                    patronymic = names[2]
                else:
                    patronymic = ""
                
                
                #str = u'%s,%s,%s.' % (code, name, post)
                #str = u'%s,%s,%s.' % (last_name, first_name, patronymic)
                #print str 
                
                try:
                    dept = Department.objects.get(code=int(code))
                    emp = Employee(
                        department = dept,
                        last_name = last_name,
                        first_name = first_name,
                        patronymic = patronymic,
                        post = post,
                        it_staff = False,
                        boss = False,
                        fired = False,
                        responsible = False,
                        )
                    emp.save()    
    
                finally:
                    pass
    
            
